package cn.hhchat.wp.controller;

import cn.hhchat.wp.config.SystemProperties;
import cn.hhchat.wp.dto.form.RegisterForm;
import cn.hhchat.wp.dto.form.UserInfoEditForm;
import cn.hhchat.wp.dto.msg.RMsg;
import cn.hhchat.wp.dto.msg.RMsgFactory;
import cn.hhchat.wp.entity.ConfigEntity;
import cn.hhchat.wp.entity.UserEntity;
import cn.hhchat.wp.enums.ConfigEnum;
import cn.hhchat.wp.exception.BadQueryException;
import cn.hhchat.wp.exception.InValidFieldsException;
import cn.hhchat.wp.security.service.JwtTokenUtil;
import cn.hhchat.wp.service.ConfigService;
import cn.hhchat.wp.service.UserService;
import cn.hhchat.wp.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * Created this one by HMH on 2017/10/22.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private String tokenHeader;

    @Autowired
    ConfigService configService;

    @Autowired
    public UserController(SystemProperties sysConfig, UserService userService, JwtTokenUtil jwtTokenUtil) {
        this.userService = userService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.tokenHeader = sysConfig.getJwt().getHeader();
    }

    @PutMapping
    public RMsg register(@Valid @RequestBody RegisterForm registerForm, BindingResult validResult) {

        ConfigEntity allowReg = configService.get(ConfigEnum.allowReg.name());
        if (!allowReg.getBoolValue()) {
            throw new BadQueryException("系统已停止注册");
        }
        if (validResult.hasErrors()) {
            throw new InValidFieldsException("数据错误：" + validResult.getFieldError().getDefaultMessage());
        }
        UserEntity userEntity = userService.createUser(registerForm);
        return RMsgFactory.ok(userEntity.toSimpleUser());
    }

    @GetMapping(value = "/getUserInfoByToken")
    public RMsg getUserInfoByToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        UserEntity userEntity = userService.getByUsername(username);
        return RMsgFactory.ok(userEntity.toSimpleUser());
    }

    @PreAuthorize("hasAnyAuthority('管理员')")
    @GetMapping(value = "/queryByEmail")
    public RMsg queryByEmail(@RequestParam String email) {
        UserEntity user = userService.getByEmail(email);
        if (null == user) {
            throw  new BadQueryException("没有找到该用户");
        }
        return RMsgFactory.ok(user.toSimpleUser());
    }

    @PostMapping("/edit")
    public RMsg edit(@Valid @RequestBody UserInfoEditForm userInfoEditForm, BindingResult validResult) {
        if (validResult.hasErrors()) {
            throw new InValidFieldsException("数据错误：" + validResult.getFieldError().getDefaultMessage());
        }
        UserEntity user = SessionUtil.getUser();
        UserEntity userEntity = userService.editUser(user, userInfoEditForm);
        return RMsgFactory.ok(userEntity.toSimpleUser());
    }

    private final UserService userService;

    private final JwtTokenUtil jwtTokenUtil;
}
